﻿//============================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-4-28
// 描 述：页面基类，所有的aspx页面继承自基类
//        页面基类提供常用的方法和常用的用户信息
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2015-4-28   江怀玉           
//=============================================================

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

using ZX.Common;
using ZX.DBModule;
using ZX.BLL.Extend;
using ZX.SYS.Library;


namespace ZX.Web.UI.Controls
{
    public partial class DefineEditForm : EditUIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateUI();

        }


        BaseEntity MasterEntity = null; 

        private void CreateUI()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string action = this.GetStringFromQueryString("action", "");
            string strFormCode = this.GetStringFromQueryString("formcode", "");
            string strFormID = this.GetStringFromQueryString("formid", Guid.Empty.ToString());
            string id = this.GetStringFromQueryString("id", "");
            BaseEntity instance = Globals.getEntity(strEntity) as BaseEntity;
            MasterEntity = instance;
            BaseBussnies BInstance = new BaseBussnies(instance);
            BaseEntity entity = null;

            if (instance == null)
            {
                instance = new DataTableBaseEntity();
               
                ((DataTableBaseEntity)instance).TableName = strEntity;
                string[] strArrary = ((DataTableBaseEntity)instance).GetKey();
                if (strArrary != null)
                {
                    ((DataTableBaseEntity)instance).TableKey = strArrary[0];
                    ((DataTableBaseEntity)instance).KeyType = strArrary[1];
                }
                ((DataTableBaseEntity)instance).CreateDT();
                if (id != "") //有ID表示编辑
                {
                    entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = strEntity;
                    ((DataTableBaseEntity)entity).TableKey = ((DataTableBaseEntity)instance).TableKey;
                    ((DataTableBaseEntity)entity).KeyType = ((DataTableBaseEntity)instance).KeyType;
                    ((DataTableBaseEntity)entity).CreateDT(id);
                    ((DataTableBaseEntity)entity).EntityJson = Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    instance = entity;
                }
                else
                {
                    if (((DataTableBaseEntity)instance).KeyType.TrimEnd() == "uniqueidentifier")
                    {
                        if (KeyValue == Guid.Empty.ToString() || String.IsNullOrEmpty(KeyValue))
                        {
                            ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).KeyType] = Guid.NewGuid();
                        }
                    }
                    else
                    {
                        if (KeyValue == Guid.Empty.ToString() || String.IsNullOrEmpty(KeyValue))
                        {
                            ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).KeyType] = 0;
                        }
                    }
                    ((DataTableBaseEntity)instance).EntityJson = Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);
                    KeyValue = instance.GetTableIdValue();
                  
                }

            }
            else
            {
                //初始化ID值
                entity = BInstance.GetEntityById(id) as BaseEntity;
                if (entity != null)
                {
                    instance = entity;
                }
            }
 
            //获取
            if (instance != null)
            {
                object O = instance.GetKeyFieldValue();
                //object O = Globals.GetPropertyValue(instance, instance.GetTableId());
                Guid? _id = ((O) == null) ? null : O as Guid?;
                //初始化ID值
                if (_id == null || _id == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, instance.GetTableId(), Guid.NewGuid());
                }
            }
            UIEntityJson = CreateInstanceJsObject(instance, entity);
            KeyValue = instance.GetTableIdValue();

            string tempCondition = "";
            if (strFormCode != "")
            {
                tempCondition = "code='" + strFormCode + "' and master_table='" + strEntity + "'";
            }
            else
            {
                tempCondition = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "id='" + strFormID + "' or master_table='" + strEntity + "'" : "id='" + strFormID + "'";
            }

            ZX.SYS.Library.SysCustomDefineForm FormEntity = _bll.GetEntityByCondition<SysCustomDefineForm>(tempCondition);
            // FormEntity = BInstance.GetEntityByCondition<t_sys_custom_define_form>(tempCondition);
            //
            if (FormEntity == null)
            {
                UIHtml = "";
                return;
            }
            if (FormEntity.MasterTableName != strEntity)
            {
                FormEntity = BInstance.GetEntityByCondition<SysCustomDefineForm>("MasterTableName='" + strEntity + "'");
            }
            //string tempCondition2 = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or TableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            if (FormEntity != null) {
                DetailsJson = FormEntity.DetailsJson;
                //Dictionary<string, string> _detail = ZX.Common.Globals.JSonToObject<Dictionary<string, string>>(DetailsJson);
                MasterEntity = instance;
                //CreateDetailInstance(DetailsJson);
                UIHtml = FormEntity.HtmlString;
            }

            if (string.IsNullOrEmpty(UIHtml))
            {
                UIHtml = LoadPageContent("");
            }
        }

        /// <summary>
        /// 明细相关数据
        /// </summary>
        public string DetailData
        {
            get;
            set;
        }

        /// <summary>
        /// 不通过Ajax，直接生成明细数据，并返回
        /// </summary>
        public string DetailsListData
        {
            get;
            set;
        }

        public string UIEntityJson
        {
            get;
            set;
        }


        /// <summary>
        /// 界面呈现的HTML
        /// </summary>
        public string UIHtml
        {
            get;
            set;
        }

        /// <summary>
        /// 加载模板页的内容
        /// </summary>
        /// <param name="page">页面地址</param>
        /// <returns></returns>
        private string LoadPageContent(string page)
        {
            return FileHelper.GetFileContent(Server.MapPath("/ExtendPage/template/html/"+page+".html"));
        }

        private void CreateDetailInstance(string DetailsJson)
        {
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                StringBuilder _detailsList = new StringBuilder("");
                if (list == null)
                {
                    return;
                }
                foreach (var _detail in list)
                {
                    string table = _detail.DetailsTableName;
                    DataTableBaseEntity entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = table;
                    string[] strArrary = ((DataTableBaseEntity)entity).GetKey();
                    if (strArrary != null)
                    {
                        ((DataTableBaseEntity)entity).TableKey = strArrary[0];
                        ((DataTableBaseEntity)entity).KeyType = strArrary[1];
                    }
                    entity.CreateDT();
                    IList<SysTableFKey> fkList = entity.GetFKey();
                    string _condtion = string.Empty;
                    if (fkList != null)
                    {
                        foreach (var e in fkList)
                        {
                            if (e.FKTableName == MasterEntity.GetTableName())
                            {
                                _condtion = _condtion == string.Empty ? e.FieldName + "='" + KeyValue + "'" : " and " + e.FieldName + "='" + KeyValue + "'";
                                FKExpression = FKExpression + e.FieldName + "='" + KeyValue + "'";
                                entity.SetFieldValue(entity, e.FieldName, KeyValue);
                            }
                        }
                    }
                    else
                    {
                        FKExpression = "1=0";
                    }

                    this._bll.entity = entity;
                    System.Data.DataTable dt = this._bll.GetDataBySqlComm(string.Format("select * from {0} where {1}", table, _condtion));
                    if (dt == null)
                    {
                        _detailsList.Append("var _" + table + "List=[];").AppendLine();
                    }
                    else
                    {
                        _detailsList.Append("var _" + table + "List="+Globals.Dtb2Json(dt)+";").AppendLine();
                    }
                    ((DataTableBaseEntity)entity).EntityJson = Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    _details .Append("var " + table + "=" + ((DataTableBaseEntity)entity).EntityJson + ";").AppendLine();
                    //_detailsList.Append("");

                }
                DetailsInstance = _details.ToString() ;
                DetailsListData = _detailsList.ToString();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string DetailsJson
        {
            get;
            set;
        }
        /// <summary>
        /// 明细表的实体
        /// </summary>
        public string DetailsInstance
        {
            get;
            set;
        }

        /// <summary>
        /// 外键表达式
        /// </summary>
        public string FKExpression
        { 
            get; 
            set; 
        }

        /// <summary>
        /// 主键ID值
        /// </summary>
        public object MasterIDValue
        {
            get;
            set;
        }
        /// <summary>
        /// 行为参数
        /// </summary>
        public String Action
        {
            get
            {
                return this.GetStringFromQueryString("action", "");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public String KeyValue
        {
            set;
            get;
        }
    }
}
